from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall import settings
from order.models import OrderInfo
from pay.models import Payment


class PaymentAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self,request,order_id):

        try:
            order = OrderInfo.objects.get(order_id=order_id,user=request.user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except  OrderInfo.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        from alipay import AliPay

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2" , # RSA 或者 RSA2
            debug = settings.ALIPAY_DEBUG  # 默认False
        )

        subject = "测试订单"

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),  # 货比类型要转换为str order.total_amount
            subject=subject,
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({'alipay_url': alipay_url})


class PayStatuAPIView(APIView):

    def put(self,request):

        data = request.query_params.dict()

        signature = data.pop("sign")

        from alipay import AliPay
        from meiduo_mall import settings
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        success = alipay.verify(data, signature)

        if success:

            trade_no = data.get('trade_no')
            out_trade_no = data.get('out_trade_no')
            # 4.  将支付宝流水号和订单id 保存起来
            Payment.objects.create(
                order_id=out_trade_no,
                trade_id=trade_no
            )

            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])

            return Response({'trade_id': trade_no})




#支付宝账号
# sfuyec0574@sandbox.com